﻿using System;
using System.Text;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using Actya.Core;
using Actya.Web.Infrastructure.ElFinderConnector;
using Actya.Web.Infrastructure.ElFinderConnector.Responses;
using Actya.Web.Mvc;

namespace Actya.Web.Controllers.CmsAdmin
{
	[Authorize(Roles = RoleNames.CmsAdministrators)]
    public class FilesController : Controller
	{
		private readonly ConnectorConfiguration _connectorConfiguration;

		public FilesController(ConnectorConfiguration connectorConfiguration)
		{
			_connectorConfiguration = connectorConfiguration;
		}

		public ActionResult Index()
		{
			return View();
		}

		public ActionResult Browse()
		{
			return View();
		}

		public ActionResult Finder()
		{
			_connectorConfiguration.ApplySettings();
			try
			{
				var dispatcher = new CommandDispatcher(this.Request);
				var response = dispatcher.DispatchCommand();

				switch (response.ContentType)
				{
					case ContentType.Json:
						return new JsonNetResult { Data = response };
					case ContentType.Ping:
						Response.End();
						break;
				}
			}
			catch (Exception ex)
			{
				var errorResponse = new ErrorResponse(ex.Message);
				errorResponse.errorData = ex.ToString();
				return new JsonNetResult {Data = errorResponse};
			}
			return new EmptyResult();
		}
    }
}
